package io.renren.modules.skate.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.Result;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.skate.dto.FAthleteDTO;
import io.renren.modules.skate.excel.FAthleteExcel;
import io.renren.modules.skate.service.FAthleteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
public class FAthleteListener extends AnalysisEventListener<FAthleteExcel> {

    private FAthleteService fAthleteService;
    private Result result;
    private static int PROCESS, TOTAL = 0;

    List<FAthleteExcel> list = new ArrayList<FAthleteExcel>();

    //构造方法
    public FAthleteListener(Result result, FAthleteService fAthleteService) {
        this.result = result;
        this.fAthleteService = fAthleteService;
    }

    @Override
    public void invoke(FAthleteExcel data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        PROCESS++;
        list.add(data);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        updData();
        TOTAL = 0;
        PROCESS = 0;
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void updData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            List<FAthleteExcel> saveList = new ArrayList();
            // 校验数据是否合法
            FAthleteExcel excel = null;
            for(int i=0; i<list.size();i++){
                excel = list.get(i);
                try{
                    fAthleteService.checkData(excel, i+2);
                }catch (Exception e){
                    e.printStackTrace();
                    result.error(e.getMessage());
                }
            }
            boolean flag = true;
            for(int i=0; i<list.size();i++){
                excel = list.get(i);
                if(excel.getCheckMsg()!=null){
                    flag = false;
                    result.setCode(500);
                    result.setMsg(excel.getCheckMsg());
                    break;
                }
            }
            if(!flag){
                return;
            }

            FAthleteDTO fAthleteDTO = null;
            for(int i=0; i<list.size();i++){
                excel = list.get(i);
                fAthleteDTO = new FAthleteDTO();
                if(StringUtils.isNotBlank(excel.getGenderStr()) && "男".equals(excel.getGenderStr())){
                    fAthleteDTO.setGender(1);
                }else if(StringUtils.isNotBlank(excel.getGenderStr()) && "女".equals(excel.getGenderStr())){
                    fAthleteDTO.setGender(0);
                }
                // 设置运动员编号，编号取日期+4位流水号
                String code = DateUtils.format(new Date(), "yyyyMMdd");
                String maxNo = fAthleteService.getMaxNo();
                // maxNo不为空，说明数据库中有数据，取最大的编号
                if(maxNo != null) {
                    String no = maxNo.substring(8);
                    if(StringUtils.isBlank(no)){
                        int noInt = 1;
                        code += String.format("%04d", noInt);
                    }
                    int noInt = Integer.parseInt(no);
                    noInt++;
                    code += String.format("%04d", noInt);
                }else {
                    code += String.format("%04d", 1);
                }
                fAthleteDTO.setNumber(code);
                // 获取当前用户的角色
                UserDetail userDetail = SecurityUser.getUser();
                if(userDetail.getClubId() != null){
                    fAthleteDTO.setClubId(userDetail.getClubId());
                }else{
                    result.error("请先选择俱乐部");
                }
                fAthleteDTO.setCreator(SecurityUser.getUserId().toString());
                fAthleteDTO.setUpdater(SecurityUser.getUserId().toString());
                fAthleteDTO.setCreateDate(new Date());
                fAthleteDTO.setUpdateDate(new Date());
                fAthleteDTO.setUsername(excel.getUsername());
                fAthleteDTO.setIdCard(excel.getIdCard());
                fAthleteDTO.setPhone(excel.getPhone());
                fAthleteService.save(fAthleteDTO);
            }
            try{
                TOTAL += saveList.size();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        log.info("存储数据库成功！");
    }
}
